package org.wutopia.labcloud.domain.order.mq.producer;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.MessageConst;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;



@Service
@RequiredArgsConstructor
@Slf4j
public class OrderProducer {
    private final RocketMQTemplate rocketMQTemplate;

    // 同步发送（可靠场景）
    public SendResult sendOrder(Long orderId) {
        Message<Long> message = MessageBuilder.withPayload(orderId)
                .setHeader(MessageConst.PROPERTY_KEYS, orderId) // 设置消息Key（追踪用）
                .build();
        return rocketMQTemplate.syncSend("ORDER-TOPIC:payTag", message); // TOPIC:Tag格式:cite[2]
    }

    // 异步发送（高性能场景）
    public void asyncSendOrder(Long event) {
        rocketMQTemplate.asyncSend("ORDER-TOPIC:payTag", event, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                log.info("异步发送成功: {}", sendResult.getMsgId());
            }
            @Override
            public void onException(Throwable e) {
                log.error("异步发送失败", e);
            }
        });
    }

    // 发送延迟消息（订单超时）
    public void sendDelayedOrder(Long orderId, int delayLevel, String tag) {
        rocketMQTemplate.syncSend("ORDER-TOPIC:"+tag,
                MessageBuilder.withPayload(orderId).build(),
                1000,  // 发送超时
                delayLevel  // 延迟级别(1=1s, 2=5s,...,18=2h):cite[2]
        );
    }
}
